package util;

import http.HttpClientUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import my.jdbc.DbConUtil;
import my.jdbc.JdbcTemplate;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import bean.BfJyys;
import bean.BfJyysDetail;
import bean.BfJyysJson;
import bean.JhysBean;
import bean.OssDailyTradeInventory;
import bean.OssMonitorInventory;
import bean.OssMonitorTimeInventory;
import bean.Sale;
import bean.StockData;
import bean.ZdStock;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 数据交换的工具类
 * 
 * @author gj
 */

public class DataExchangeUtil {
	private static final Log log = LogFactory.getLog(DataExchangeUtil.class);
	private static ObjectMapper mapper = new ObjectMapper();
	public static Map<String, String> appGkStationCodeKeyValue = new HashMap<String, String>();
	public static Map<String, String> gkAppStationCodeKeyValue = new HashMap<String, String>();

	private static final int PAGE_SIZE = 500;// 发送接口数据的条数

	// 上传进货验收数据
	public static void sendJhysData(List<BfJyysJson> jhysListJsonData, String preInfo) {

		Map<Integer, List<BfJyysJson>> jhysListJsonMap = DataExchangeUtil.listDataToManyListData(jhysListJsonData, DataExchangeUtil.PAGE_SIZE);

		for (int i = 0; i < jhysListJsonMap.size(); i++) {
			List<BfJyysJson> jhysListJson = jhysListJsonMap.get(i);
			String jhysListJsonString = "[]";
			try {
				jhysListJsonString = mapper.writeValueAsString(jhysListJson);
				log.info(preInfo + ": ===jhysListJsonString===" + jhysListJsonString);

				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				nvps.add(new BasicNameValuePair("params", jhysListJsonString));
				HttpClientUtil.sendPost("http://10.190.1.165:8080/bfJyys/insertBfJyys.do", nvps, "进货验收数据");

			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}

	}

	// 上传时点库存数据
	public static void sendSdStockData(List<StockData> sdStockJsonListData) {
		Map<Integer, List<StockData>> sdStockJsonListMap = DataExchangeUtil.listDataToManyListData(sdStockJsonListData, DataExchangeUtil.PAGE_SIZE);
		for (int i = 0; i < sdStockJsonListMap.size(); i++) {
			List<StockData> sdStockJsonList = sdStockJsonListMap.get(i);
			String sdStockJsonListString = "[]";
			try {
				sdStockJsonListString = mapper.writeValueAsString(sdStockJsonList);
				// log.info("DataExchangeUtil===sdStockJsonListString===" + sdStockJsonListString);

				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				nvps.add(new BasicNameValuePair("params", sdStockJsonListString));
				HttpClientUtil.sendPost("http://10.190.1.165:8080/stockData/insertStockHoutData.do", nvps, "时点库存数据");
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	// 上传销售数据
	public static void sendSaleData(List<Sale> saleJsonListData) {
		Map<Integer, List<Sale>> saleJsonListMap = DataExchangeUtil.listDataToManyListData(saleJsonListData, DataExchangeUtil.PAGE_SIZE);
		for (int i = 0; i < saleJsonListMap.size(); i++) {
			List<Sale> saleJsonList = saleJsonListMap.get(i);
			String saleJsonListString = "[]";
			try {
				saleJsonListString = mapper.writeValueAsString(saleJsonList);
				// log.info("DataExchangeUtil===saleJsonListString===" + saleJsonListString);

				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				nvps.add(new BasicNameValuePair("params", saleJsonListString));
				HttpClientUtil.sendPost("http://10.190.1.165:8080/sale/getSale.do", nvps, "销售数据");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 上传整点库存
	public static void sendZdStockData(List<ZdStock> zdStockJsonListData) {
		Map<Integer, List<ZdStock>> zdStockJsonListMap = DataExchangeUtil.listDataToManyListData(zdStockJsonListData, DataExchangeUtil.PAGE_SIZE);
		for (int i = 0; i < zdStockJsonListMap.size(); i++) {
			List<ZdStock> zdStockJsonList = zdStockJsonListMap.get(i);
			String zdStockJsonListString = "[]";
			try {
				zdStockJsonListString = mapper.writeValueAsString(zdStockJsonList);
				// log.info("DataExchangeUtil===zdStockJsonListString===" + zdStockJsonListString);

				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				nvps.add(new BasicNameValuePair("params", zdStockJsonListString));
				HttpClientUtil.sendPost("http://10.190.1.165:8080/stockData/insertStockData.do", nvps, "整点库存数据");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	// 接口数据封装
	public static BfJyysDetail jhysDetailJsonSetValue(JhysBean jhysBean1) {
		BfJyysDetail jhysDetail = new BfJyysDetail();
		jhysDetail.setDeliveryno(jhysBean1.getDeliveryNo());
		jhysDetail.setManualno(jhysBean1.getManualNo());
		jhysDetail.setOilcan(jhysBean1.getOilCan() + "");
		jhysDetail.setShift(jhysBean1.getShift());
		jhysDetail.setBegintime(jhysBean1.getBeginTimeb());
		jhysDetail.setEndtime(jhysBean1.getEndTimeb());
		jhysDetail.setDischargel(jhysBean1.getDischargeL());
		jhysDetail.setBeginoilheight(jhysBean1.getBeginOilHeight());
		jhysDetail.setBeginwaterheight(jhysBean1.getBeginWaterHeight());
		jhysDetail.setBeginoill(jhysBean1.getBeginOilL());
		jhysDetail.setBeginv20l(jhysBean1.getBeginV20L());
		jhysDetail.setBegintemperature(jhysBean1.getBeginTemperature());
		jhysDetail.setEndoilheight(jhysBean1.getEndOilHeight());
		jhysDetail.setEndwaterheight(jhysBean1.getEndWaterHeight());
		jhysDetail.setEndoill(jhysBean1.getEndOilL());
		jhysDetail.setEndv20l(jhysBean1.getEndV20L());
		jhysDetail.setEndtemperature(jhysBean1.getEndTemperature());
		jhysDetail.setBeginentertype(jhysBean1.getEnterType() == null ? 0 : jhysBean1.getEnterType());
		jhysDetail.setEndentertype(jhysBean1.getEnterType() == null ? 0 : jhysBean1.getEnterType());
		jhysDetail.setDuringsales(jhysBean1.getDuringSalesb());
		jhysDetail.setForcecancelstable(jhysBean1.getForceCancelStable() == null ? 0 : jhysBean1.getForceCancelStable());
		jhysDetail.setCanversion(jhysBean1.getCanVersion());
		return jhysDetail;
	}

	public static BfJyys jhysJsonSetValue(String stationCode, JhysBean jhysBean) {
		BfJyys jhys = new BfJyys();
		jhys.setNodeno(stationCode);
		jhys.setDeliveryno(jhysBean.getDeliveryNo());
		jhys.setManualno(jhysBean.getManualNo());
		jhys.setOilno(jhysBean.getOilNo());
		jhys.setDischargeloss(jhysBean.getDischargeLoss());
		jhys.setDischargelossv20(jhysBean.getDischargeLossV20());
		jhys.setDischargerate(jhysBean.getDischargeRate());
		jhys.setDischargeratev20(jhysBean.getDischargeRateV20());
		jhys.setPlanl(jhysBean.getPlanL());
		jhys.setRealreceivel(jhysBean.getRealReceiveL());
		jhys.setHeightempey(jhysBean.getHeightEmpey());
		jhys.setHeighttotal(jhysBean.getHeightTotal());
		jhys.setPlumbunbankoperator(jhysBean.getPlumbunBankOperator());
		jhys.setCalculateoperator(jhysBean.getCalculateOperator());
		jhys.setBackbankno(jhysBean.getBackBankNo());
		jhys.setCantrucktemp(jhysBean.getCanTruckTemp());
		jhys.setRealgetl(jhysBean.getRealGetL());
		jhys.setRealgetlv20(jhysBean.getRealGetLV20());
		jhys.setDuringsales(jhysBean.getDuringSales());
		jhys.setBegintime(jhysBean.getBeginTime());
		jhys.setEndtime(jhysBean.getEndTime());
		jhys.setIndemnityloss(jhysBean.getIndemnityLoss());
		jhys.setInstationtime(jhysBean.getInStationTime());
		jhys.setShift(jhysBean.getShift());
		return jhys;
	}

	public static ZdStock zdStockJsonSetValue(String stationCode, OssMonitorInventory zdStock) {
		ZdStock zdJson = new ZdStock();
		zdJson.setNodeno(stationCode);
		zdJson.setOilcanno(zdStock.getOilCanNo() + "");
		zdJson.setOilno(zdStock.getOilNo());
		zdJson.setDate(zdStock.getdATE());
		zdJson.setTime(zdStock.gettIME());
		zdJson.setStandcubage(zdStock.getStandCubage());
		zdJson.setTotalheight(zdStock.getTotalHeight());
		zdJson.setOilcubage(zdStock.getOilCubage());
		zdJson.setWaterheight(zdStock.getWaterHeight());
		zdJson.setWaterbulk(zdStock.getWaterBulk());
		zdJson.setTemp(zdStock.getTemp());
		zdJson.setEmptycubage(zdStock.getEmptyCubage());
		zdJson.setTemp1(zdStock.getTemp1());
		zdJson.setTemp2(zdStock.getTemp2());
		zdJson.setTemp3(zdStock.getTemp3());
		zdJson.setTemp4(zdStock.getTemp4());
		zdJson.setTemp5(zdStock.getTemp5());
		zdJson.setApparentdensity(zdStock.getApparentDensity());
		zdJson.setStanddensity(zdStock.getStandDensity());
		zdJson.setVersion("");
		return zdJson;
	}

	public static Sale saleJsonSetValue(String stationCode, OssDailyTradeInventory sale) {
		Sale saleJson = new Sale();
		saleJson.setNodeno(stationCode);
		saleJson.setMacno(sale.getMacNo());
		saleJson.setTtc(sale.gettTC());
		saleJson.setOilgun(sale.getOilGun());
		saleJson.setOilcan(sale.getOilCan() + "");
		saleJson.setOilno(sale.getOilNo());
		// 泵码
		saleJson.setPumpno("");
		saleJson.setTakedate(sale.getTakeDate());
		saleJson.setOpetime(sale.getOpeTime());
		saleJson.setStockdate(sale.getStockDate());
		saleJson.setStocktime(sale.getStockTime());
		// 加油升数
		saleJson.setLiter(0.0);
		// 回灌标记
		saleJson.setCheckmode("");
		saleJson.setHeighttotal(sale.getHeightTotal());
		saleJson.setHeightwater(sale.getHeightWater());
		saleJson.setOill(sale.getOilL());
		saleJson.setStandardl(sale.getStandardL());
		saleJson.setEmptyl(sale.getEmptyL());
		saleJson.setWaterl(sale.getWaterL());
		saleJson.setOiltemp(sale.getOilTemp());
		saleJson.setDensity(sale.getDensity());
		saleJson.setDensitystandard(sale.getDensityStandard());
		saleJson.setShift(sale.getShift());
		saleJson.setRemark(sale.getRemark());
		return saleJson;
	}

	public static StockData sdStockJsonSetValue(String stationCode, OssMonitorTimeInventory sdstock) {
		StockData sdstockJson = new StockData();
		sdstockJson.setNodeno(stationCode);
		sdstockJson.setOilcan(sdstock.getOilCan() + "");
		sdstockJson.setOilno(sdstock.getOilNo());
		sdstockJson.setStoretime(sdstock.getStoreTime());
		sdstockJson.setStandardl(sdstock.getStandardL());
		sdstockJson.setHeighttotal(sdstock.getHeightTotal());
		sdstockJson.setOill(sdstock.getOilL());
		sdstockJson.setHeightwater(sdstock.getHeightWater());
		sdstockJson.setWaterl(sdstock.getWaterL());
		sdstockJson.setTemperature(sdstock.getTemperature());
		sdstockJson.setVolumeempty(sdstock.getVolumeEmpty());
		sdstockJson.setTemp1(sdstock.getTemp1());
		sdstockJson.setTemp2(sdstock.getTemp2());
		sdstockJson.setTemp3(sdstock.getTemp3());
		sdstockJson.setTemp4(sdstock.getTemp4());
		sdstockJson.setTemp5(sdstock.getTemp5());
		sdstockJson.setDensities(sdstock.getDensities());
		sdstockJson.setDensitiesstandard(sdstock.getDensitiesStandard());
		sdstockJson.setCreatetime(sdstock.getCreateTime());
		sdstockJson.setShift(sdstock.getShift());
		sdstockJson.setVersion("");// 容积表版本号
		sdstockJson.setTranstatus(sdstock.getTranStatus());
		return sdstockJson;
	}

	public static void selectStationCodeKeyValue() {
		String sql = " SELECT station_code,control_station_code FROM SH_STATION WHERE control_station_code IS NOT NULL AND control_station_code <> '' ";
		List<Object[]> stationCodeList = JdbcTemplate.queryListFieldInfoByBean(DbConUtil.get162ptCon(), sql, null, DbConUtil.TYPE_NAME_162PT);
		for (Object[] stationCode : stationCodeList) {
			appGkStationCodeKeyValue.put(stationCode[0].toString(), stationCode[1].toString());
			gkAppStationCodeKeyValue.put(stationCode[1].toString(), stationCode[0].toString());
		}
	}

	// 油站代码转换(管控转零管)
	public static String getAppStationCode(String gkStationCode) {
		String appStationCode = gkAppStationCodeKeyValue.get(gkStationCode);
		return StringUtils.isBlank(appStationCode) ? gkStationCode : appStationCode;
	}

	// 油站代码转换(零管转管控)
	public static String getGkStationCode(String appStationCode) {
		String gkStationCode = appGkStationCodeKeyValue.get(appStationCode);
		return StringUtils.isBlank(gkStationCode) ? appStationCode : gkStationCode;
	}

	// 查询油站的IP地址
	public static String getIpAddressByStationCode(String appStationCode) {
		String IPSql = " SELECT ip FROM SH_STATION WHERE station_code = '" + appStationCode + "' ";
		Object[] ipInfo = JdbcTemplate.queryFieldInfoByFields(DbConUtil.get162ptCon(), IPSql, null, DbConUtil.TYPE_NAME_162PT);
		String ipAddress = ipInfo == null ? "" : (ipInfo[0] == null ? "" : ipInfo[0].toString());
		return ipAddress;
	}

	// 检测IP地址和油站代码是否一致
	public static boolean isOkForStationAndIP(String ipAddress, String gkStationCode) {
		Object[] departmentInfo = JdbcTemplate.queryFieldInfoByBean(DbConUtil.getGsmappCon(ipAddress), "SELECT * FROM oss_sysmanage_department", null, ipAddress);
		if (departmentInfo[0].equals(gkStationCode)) {
			return true;
		}
		return false;
	}

	// 检测IP是否能连上
	public static boolean isOkForIpAddressCon(String ipAddress) {
		boolean isIPAddressConOK = false;
		// 默认连接2次
		for (int i = 0; i < 2; i++) {
			isIPAddressConOK = DbConUtil.isOKGsmappCon(ipAddress);
			if (isIPAddressConOK) {
				break;
			}
		}
		return isIPAddressConOK;
	}

	/**
	 * 将一个list切分成多个list,可以指定切分成的list的大小
	 * 
	 * @param data
	 * @param pageSize
	 * @return Map<Integer, List<T>>
	 */
	public static <T> Map<Integer, List<T>> listDataToManyListData(List<T> data, int pageSize) {
		int total = data.size();
		Map<Integer, List<T>> md = new HashMap<Integer, List<T>>();
		int count = total / pageSize;
		if (total % pageSize != 0) {
			count++;
		}
		for (int i = 0; i < count; i++) {
			List<T> list = new ArrayList<T>();
			for (int j = 1; j <= total; j++) {
				if (j > i * pageSize) {
					list.add(data.get(j - 1));
					if (j == (i + 1) * pageSize) {
						break;
					}
				}
			}
			md.put(i, list);
		}
		return md;
	}

	public static boolean isAjaxRequest(HttpServletRequest request) {
		return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
	}

	public static void main(String[] args) {
		System.out.println(isOkForIpAddressCon("10.190.35.6"));
	}

}
